<?php

namespace app\common\model;

use think\facade\Cache;

class AuthRuleModel extends BaseModel
{

  protected $table = 'auth_rule';

  /**
   * 获取列表
   * @param bool $refresh
   * @return array|mixed
   * @throws \Exception
   */
  public function getList($refresh = false)
  {
    if (Cache::has('auth_rule') && $refresh == false) return Cache::get('auth_rule');
    $list     = $this->order("show_order asc")->select()->toArray();
    $tree = $this->formatTree($list,'title');
    cache('auth_rule', $tree);
    return $tree;
  }

  /**
   * 添加
   * @param $data
   * @return AuthRuleModel|\think\Model
   * @throws \Exception
   */
  public function add($data)
  {
    if ($this->where('name', $data['name'])->find()) abort(500, '改规则已存在');
    return self::create($data);
  }

  /**
   * 修改规则
   * @param $data
   * @return mixed
   * @throws \Exception
   */
  public function edit($data)
  {
    $info = $this->where('id', $data['id'])->find();
    if (empty($info)) abort(500, '未找到对应数据');
    if ($info['name'] != $data['name'] && $this->where('name', $data['name'])->find()) {
      abort(500, '改规则已存在');
    }
    return self::update($data);
  }

  /**
   * 删除规则
   * @param $id
   * @return mixed
   * @throws \Exception
   */
  public function del($id)
  {
    if ($this->where('pid', $id)->find()) abort(500, '存在下级规则，不允许删除');
    if (AuthGroupModel::whereFindInSet('rules', $id)->find()) abort(500, '该规则已使用，不允许删除');
    return $this->where('id', $id)->delete();
  }

}
